<template>
	<div class="page-moreLimit">
		<div class="limit-body">
			<van-pull-refresh :style="{ height: scollHeight + 'px' }" class="scroller" v-model="loading" @refresh="onPullDownRefresh">
				<van-list v-model="loading" :finished="finish" finished-text="没有更多了" @load="onReachBottom">
					<div class="goods-items">
						<template>
							<goods-item
								v-for="(item3, index3) in list"
								:key="index3"
								:item="item3"
								:index="index3"
								:tab-index="index3"
								:showLimit="true"
								@grab="onItemGrab"
								@copy="onItemCopy"
								@change="onItemChange"
								@ins-balance="onInsBalance"
							></goods-item>
						</template>
					</div>
				</van-list>
			</van-pull-refresh>
		</div>

		<!-- 复制口令 -->
		<div class="pupop-copy-tkl">
			<cl-popup direction="center" :visible.sync="copyTkl.visible">
				<img src="@/assets/2/images/toast-success.png" />

				<p class="fa">{{ bwbt_conf.tklTemplate }}复制成功</p>
				<p class="fa">打开【{{ bwbt_conf.openTemplate }}】购买吧</p>
				<p class="fb">优惠券到期时间</p>

				<div class="countdown">
					<cl-countdown :splitor="['分', '秒']" :layout="['hour', 'minute', 'second']" :datetime="endTime"></cl-countdown>
				</div>

				<span class="cl-icon-close" @click="copyTkl.visible = false"></span>
			</cl-popup>
		</div>

		<!-- 抢到了 -->
		<div class="popup-snatched _copy-btn" :data-clipboard-span="snatched.tkl">
			<cl-popup direction="center" :visible.sync="snatched.visible">
				<img class="popup-snatched__cover" src="@/assets/2/images/grabbg.png" />

				<div class="popup-snatched__tips">
					<p>打开【{{ bwbt_conf.openTemplate }}】购买吧</p>
					<div class="countdown">
						<p>请在</p>
						<cl-countdown :splitor="['分', '秒']" :layout="['hour', 'minute', 'second']" :datetime="endTime"></cl-countdown>
						<p>前购买</p>
					</div>
				</div>

				<button class="popup-snatched__btn _copy-btn" :data-clipboard-text="snatched.tkl" @click="snatched.visible = false">
					我知道了
				</button>
			</cl-popup>
		</div>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import Clipboard from 'clipboard';
import moment from 'moment';
import VanTab from 'vant/lib/tab';
import VanTabs from 'vant/lib/tabs';
import VanSkeleton from 'vant/lib/skeleton';
import Toast from 'vant/lib/toast';

import GoodsItem from './components/goods-item';
import Rules from './components/rules';
import Share from './components/share';
import BalancePopup from './components/balance-popup';
import Winners from './components/winners';
import ShopBtn from './components/shop-btn';
import RedPackagePopup from './components/red-package';
import TaskPopup from './components/task/popup';
import Banner from './components/banner';
import ClCountdown from '@/components/countdown';
import ClPopup from '@/components/popup';

import $ from 'jquery';

import { getQueryString } from '@/utils';

export default {
	components: {
		GoodsItem,
		Rules,
		Share,
		BalancePopup,
		Winners,
		ShopBtn,
		RedPackagePopup,
		Banner,
		ClCountdown,
		ClPopup,
		TaskPopup,
		VanTabs,
		VanTab,
		VanSkeleton
	},

	data() {
		return {
			current: 0,
			finish: false,
			loading: false,
			skeletonLoading: false,
			list: [],
			scrollTop: 0,
			scollHeight: 0,
			endTime: '',
			snatched: {
				visible: false,
				timer: null,
				tkl: ''
			},
			snatchedBanner: {
				visible: false
			},
			totb: {
				visible: false
			},
			copyTkl: {
				visible: false,
				timer: null
			},
			done: false,
			selects: {
				category: ''
			},
			categoryMenu: {
				visible: false
			},
			pageSize: '4'
		};
	},

	computed: {
		...mapGetters(['bwbt_userInfo', 'token', 'bwbt_conf'])
	},

	watch: {
		token(val) {
			if (val) {
				this.getUserInfo();
			}
		}
	},

	activated() {
		// this.$service.bwbt.bwbtUser.shareBwbt();

		this.loading = true;

		const { category } = this.$route.query;

		// 获取类目
		this.selects.category = category || getQueryString('category') || '';

		if (this.token) {
			this.getUserInfo();
		}
	},

	mounted() {
		this.scollHeight = document.documentElement.clientHeight;
		window.addEventListener('scroll', () => {
			this.scrollTop = $(document).scrollTop();
		});

		const mo = function(e) {
			e.preventDefault();
		};

		function stop() {
			document.querySelector('.header').addEventListener('touchmove', mo, { passive: false }); //禁止页面滑动
		}
	},
	created() {
		console.log('onload');
		console.log(this.$service);
		this.loading = true;
		//获取限时限量商品
		this.$service.bwbt.bwbtGoods
			.marketGoods({
				page: '1',
				size: this.pageSize
			})
			.then(res => {
				console.log(res.list);
				this.list = res.list;
				this.current = res.pagination.page;
				this.size = res.pagination.size;
				this.loading = false;
			})
			.catch(err => {
				console.error(err);
			});
	},
	methods: {
		getUserInfo() {
			Toast.loading({
				message: '加载中'
			});

			this.$store
				.dispatch('GET_BWBT_USERINFO')
				.then(res => {
					if (res.config.newPersonPageType == 1 && res.user.newPerson == 1 && res.user.numToday === 0) {
						this.$refs['red-package-popup'].open();
					}
					// 开始倒计时
					this.startCountdown();

					// 是否注册复制
					if (res.config.orderConfig.includes('copy')) {
						new Clipboard(`._copy-btn`);
					}

					// banner复制
					new Clipboard(`.copy-btn`).on('success', e => {
						this.totb.visible = true;
						e.clearSelection();
					});

					Toast.clear();
				})
				.catch(err => {
					console.error(err);
					this.loading = false;
					Toast.clear();
				});
		},
		startCountdown() {
			let t = Number(this.bwbt_conf.countDownTime || '60') || '60';
			let now = null;

			if (t != localStorage.getItem('countdown_mode')) {
				localStorage.removeItem('countdown');
			}

			if (t < 0) {
				now = moment().format('YYYY-MM-DD 23:59:59');
			} else {
				if (isNaN(t)) {
					t = 60;
				}
				now = moment()
					.add(t, 'minute')
					.format('YYYY-MM-DD HH:mm:ss');
			}

			let endTime = localStorage.getItem('countdown');

			if (!endTime) {
				endTime = now;
			} else {
				if (moment(endTime).isBefore(moment())) {
					endTime = now;
				}
			}

			localStorage.setItem('countdown', endTime);
			localStorage.setItem('countdown_mode', t);

			this.endTime = endTime;
		},
		onItemGrab(tkl) {
			this.snatched.visible = true;
			this.snatched.tkl = tkl;
			clearInterval(this.snatched.timer);

			if (this.bwbt_conf.orderConfig == 'copy-close') {
				this.snatched.timer = setTimeout(() => {
					this.snatched.visible = false;
				}, 3000);
			}
		},

		// 修改其他列表同个商品的信息
		onItemChange(item) {
			this.list.forEach(e => {
				if (e.children) {
					e.children.forEach(a => {
						if (a.gid == item.gid) {
							Object.assign(a, item);
						}
					});
				}
			});
		},

		onItemCopy() {
			this.copyTkl.visible = true;
			clearInterval(this.copyTkl.timer);

			this.copyTkl.timer = setTimeout(() => {
				this.copyTkl.visible = false;
			}, 3000);
		},

		onInsBalance() {
			this.$refs['balance-popup'].open();
		},

		refresh(params) {
			const page = params.page || 1;
			console.log('当前页码' + page);
			this.loading = true;
			return new Promise((resolve, reject) => {
				this.$service.bwbt.bwbtGoods
					.marketGoods({
						page: page,
						size: this.pageSize
					})
					.then(res => {
						// 追加还是重置
						if (!page || page == 1) {
							this.list = res.list;
						} else {
							this.list.push(...res.list);
						}
						this.current = res.pagination.page;
						this.size = res.pagination.size;
						this.finish = this.list.length == res.pagination.total;
						this.loading = false;
						this.skeletonLoading = false;

						resolve();
					})
					.catch(err => {
						this.loading = false;
						this.skeletonLoading = false;
						console.error(err);
					});
			});

			// const item = this.list[this.current];

			this.loading = true;
			// item.pagination.page = params.page || 1;
			this.skeletonLoading = true;
		},

		onReachBottom() {
			if (this.list.length > 0) {
				this.refresh({
					page: this.current + 1
				});
			}
		},

		async onPullDownRefresh() {
			this.loading = true;

			await this.refresh({
				page: 1
			});

			this.loading = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.page-moreLimit {
	font-size: 24px;
}
.limit_header {
	font-size: 32px;
	font-weight: bold;
	background-color: #fff;
	padding: 20px;
	box-sizing: border-box;
	text-align: center;
	position: relative;
}
.limit-body {
	padding: 20px;
}
.back {
	position: absolute;
	left: 20px;
	top: 28px;
	width: 32px;
	height: 32px;
}
.pupop-copy-tkl {
	letter-spacing: 1px;

	/deep/.cl-popup {
		border-radius: 10px;

		&__container {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 500px;
		}
	}

	img {
		height: 80px;
		width: 80px;
		margin: 50px 0 50px 0;
	}

	.fa {
		font-size: 28px;
	}

	.fb {
		font-size: 24px;
		color: #999;
		margin-top: 50px;
	}

	.countdown {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		margin-bottom: 20px;
	}

	.cl-icon-close {
		position: absolute;
		right: -5px;
		top: 5px;
		height: 60px;
		width: 60px;
		font-size: 40px;
	}
}
.popup-snatched {
	background-color: #fff;
	/deep/.cl-popup {
		background-color: transparent;

		&__container {
			display: flex;
			flex-direction: column;
			align-items: center;
		}
	}

	&__cover {
		height: 668px;
		width: 668px;
	}

	&__tips {
		position: absolute;
		left: -5px;
		bottom: 250px;
		width: 100%;
		color: #fff;
		text-align: center;
		letter-spacing: 1px;

		& > span {
			&:first-child {
				font-size: 28px;
				margin-bottom: 10px;
			}
		}

		.countdown {
			display: flex;
			align-items: center;
			justify-content: center;

			/deep/.cl-countdown__number {
				background-color: transparent !important;
				font-size: 24px;
				padding: 0 5px;
				margin: 5px 0 !important;
			}
		}
	}

	&__btn {
		height: 70px;
		line-height: 70px;
		width: 200px;
		color: #fff;
		background-color: #f70114;
		box-shadow: 0 6px 10px 2px rgba(0, 0, 0, 0.4);
		font-size: 26px;
		border-radius: 70px;
		position: relative;
		top: -80px;
		margin: 0 auto;
		letter-spacing: 1px;
		border: 0;

		&::after {
			border: 0;
		}
	}
}
/deep/.cl-countdown__number {
	background-color: #f70114 !important;
	color: #fff;
	height: 40px;
	line-height: 40px;
	padding: 0 5px;
	border-radius: 6px;
	margin: 10px 10px !important;
	font-size: 12px;
}

/deep/.cl-countdown__splitor {
	font-size: 12px;
	position: relative;
	top: -2px;
}
</style>
